<template>
	<div class="pageViewDesigner">
		<iframe
			ref="appiframe"
			:src="url"
			frameborder="0"
			style="width: 100%; height: 100%"
			@load="sendMessage"
		></iframe>
	</div>
</template>

<script>
import { mapMutations, mapGetters } from 'vuex'
import {
	tCustomerFormJsonUpdate,
	syscustomerformGetModel,
} from '@/http/customerForm'
let baseUrl = window.location.origin
export default {
	name: 'AppFormGenerator',
	data() {
		return {
			// url: 'http://192.168.1.40:8182/#/?id=10',
			id: '',
			formData: {},
		}
	},
	computed: {
		...mapGetters(['tabsList']),
		url() {
			// return `${window.location.origin}/static/h5/index.html/#/pages/index/index?id=${this.id}`
			return `${baseUrl}/static/h5/index.html#/pages/index/index?id=${this.id}`
		},
	},
	watch: {
		$route: {
			handler: function (val) {
				this.id = val.params.id
				this.syscustomerformGetModel({ id: val.params.id })
			},
			immediate: true,
		},
	},
	mounted() {
		this.iframeWin = this.$refs.appiframe.contentWindow
		this.iframeWin.saveAppFormJson = this.saveAppFormJson
	},
	methods: {
		...mapMutations('common', ['CLOSETAB', 'CHANGE_DEFAULTACTIVE']),
		closeCurTab() {
			let item = this.tabsList.find(i => i.path === this.$route.path)
			// console.log(item)
			this.CLOSETAB(item.path)
			let art = this.tabsList[this.tabsList.length - 1]
			if (art.componentName === 'MainView') {
				art = this.tabsList[this.tabsList.length - 2]
			}
			this.$router.push(art.path)
			this.CHANGE_DEFAULTACTIVE(art.path)
		},
		syscustomerformGetModel(data) {
			syscustomerformGetModel(data).then(({ data }) => {
				// console.log(data, 22222)
				this.formData = { ...data.data }
			})
		},
		sendMessage() {
			// console.log(this.iframeWin, 1111)
			const t = JSON.parse(window.localStorage.getItem('userMsg'))
			const token = this.$store.state.user.userMsg.token || t ? t.token : ''
			// if (token) {
			// 	config.headers.Authorization = `${token}`
			// }
			this.iframeWin.postMessage({ Authorization: `${token}` })
		},
		saveAppFormJson(data, bol) {
			// console.log(data, 111)
			let res = JSON.parse(data)
			let obj = Object.assign({}, this.formData)
			obj.formJson = JSON.stringify(res)
			tCustomerFormJsonUpdate(obj).then(({ data }) => {
				if (data?.head?.code == 200) {
					if (!bol) {
						this.$confirm('保存成功，是否关闭当前页面?', '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'success',
						})
							.then(() => {
								this.closeCurTab()
							})
							.catch(() => {})
					}
				}
			})
		},
	},
}
</script>

<style lang="scss" scoped>
.pageViewDesigner {
	height: 100%;
	width: 100%;
}
</style>
